import { cloneDeep } from 'lodash-es'
import { http } from '@/utils/http'
import { ElMessage } from 'element-plus'
import { getPlatformUser, getMoneyLimit } from '@/api/user'
import { checkRoles } from '@/stores/roles'
import { initiaStore } from '@/stores/initialization.js'
import _ from 'lodash-es'

export const ambientAddStore = () => {
    const userStore = useUserStore()
    const router = useRouter()
    const route = useRoute();
    const initiaStores = initiaStore()
    const state = reactive({
        routeData: {},
        title: '新建浏览器环境',
        updateFormData: {},
        expandDiv: false,
        loading: false,
        menuList: [
            {
                value: 'base',
                label: '基础设置',
                active: true,
                scrollHeight: 0,
                offsetTop: 0,
                ref: null

            }, {
                value: 'proxy',
                label: '代理信息',
                active: false,
                scrollHeight: 0,
                offsetTop: 0,
                ref: null
            }, {
                value: 'user',
                label: '账号信息',
                active: false,
                scrollHeight: 0,
                offsetTop: 0,
                ref: null
            }, {
                value: 'hign',
                label: '高级设置',
                active: false,
                scrollHeight: 0,
                offsetTop: 0,
                ref: null
            },
        ],
        activeCollapse: ['base', 'proxy'],
        formData: {},

        listScrollbar: null,


        preferenceDialog: false,
        formData_copy: {},
        map: {}
    })

    const clickReturn = () => {
        router.replace({
            name: 'home',
            query: { manager: state.routeData.manager } // 使用查询参数传递
        });
    }

    const clickmenu = (row) => {

        state.menuList.forEach(item => {
            if (item.value == row.value) {
                item.active = true
            } else {
                item.active = false
            }
        });
        state.listScrollbar.setScrollTop(row.ref.offsetTop)

    }

    const clickcheckIP = () => {
        state.formData.proxy.is_check = 1

        setTimeout(() => {
            if (state.formData.proxy.is_check != 0) {
                state.formData.proxy.is_check = 2
            }
        }, 5000);
    }

    const clickcancelCheckip = () => {
        state.formData.proxy.is_check = 0
    }

    const changeProxyMode = () => {
        if (state.formData.proxy.mode == 0) {
            state.map.procyType = [
                {
                    value: '-1',
                    label: '不使用代理'
                }, {
                    value: 'http',
                    label: 'HTTP'
                }, {
                    value: 'https',
                    label: 'HTTPS'
                }, {
                    value: 'SSH',
                    label: 'SSH'
                }, {
                    value: 'Socks5',
                    label: 'Socks5'
                }, {
                    value: 'Oxylabsauto',
                    label: 'Oxylabsauto （动态代理）'
                }, {
                    value: 'Lumauto',
                    label: 'Lumauto （动态代理）'
                }, {
                    value: 'Luminati',
                    label: 'Luminati （静态代理）'
                }, {
                    value: 'smartproxy',
                    label: 'smartproxy （动态代理）'
                }, {
                    value: 'Iphtml',
                    label: 'Iphtml（动态代理）'
                }, {
                    value: 'IPIDEA',
                    label: 'IPIDEA（动态代理）'
                },
            ]
            state.formData.proxy.type = '-1'
        } else if (state.formData.proxy.mode == 1) {
            state.map.procyType = [
                {
                    value: 'http',
                    label: 'HTTP'
                }, {
                    value: 'https',
                    label: 'HTTPS'
                }, {
                    value: 'Socks5',
                    label: 'Socks5'
                }
            ]
            state.formData.proxy.type = 'http'
        }
    }


    // 获取语言
    const getLanguages = () => {
        http.get('/environment/get_languages').then(res => {
            state.map.languages = res.data.list.map(item => {
                return {
                    value: item.language_code,
                    label: item.language_name
                }
            })
        })
    }

    // 获取字体
    const getFonts = () => {
        http.get('/environment/get_fonts').then(res => {
            state.map.fonts = res.data.list.map(item => {
                return {
                    value: item.font,
                    label: item.font
                }
            })
        })
    }

    // 获取时区
    const getTimeZones = () => {
        http.get('/environment/get_time_zones').then(res => {
            state.map.timeZones = res.data.list.map(item => {
                return {
                    value: item.id,
                    label: `${item.code} ${item.timezone}`
                }
            })
        })
    }

    // 获取国家
    const getCountries = () => {
        http.get('/environment/get_countries').then(res => {
            state.map.countryOptions = res.data.list.map(item => {
                return {
                    value: item.country_code,
                    label: item.country_name
                }
            })
        })
    }

    // 获取平台
    const getPlatforms = () => {
        http.get('/environment/get_platforms').then(res => {
            state.map.bc_types = res.data.list.map(item => {
                return {
                    value: item.id,
                    label: item.platform_name,
                    data: item
                }
            })
        })
    }

    // 获取UA版本
    const getUaVersion = () => {
        http.get(`/environment/get_ua_version?browser=ChroBrowser`).then(res => {
            state.map.inheritOptions = res.data.version.map(item => {
                return {
                    value: item,
                    label: item
                }
            })
        })
    }

    // 获取分组
    const getGroupList = () => {
        http.get(`/environment/get_groups?page=1&page_size=9999`).then(res => {
            state.map.groupList = res.data.list.map(item => {
                return {
                    value: item.id,
                    label: item.name
                }
            })
        })
    }

    const getPhone = (value) => {
        state.formData.base.operate = value
        if (value == 'Android' || value == 'iOS') {
            http.get(`/environment/get_phone?system=${state.formData.base.operate}`).then(res => {
                state.map.modelOptions = res.data.list.map(item => {
                    return {
                        value: item.phone_type,
                        label: item.phone_type
                    }
                })

                state.formData.base.model = state.map.modelOptions[0].value
            })
        }

        getUserAgent()

    }

    const getUserAgent = () => {
        let body = {
            params: {
                version: '',
                system: state.formData.base.operate,
                browser: state.formData.base.browser.type
            }
        }

        if (!state.formData.base.userAgent.inherit.includes('all')) {
            body.params.version = state.formData.base.userAgent.inherit.join(',')
        } else {
            delete body.params.version
        }


        http.get(`/environment/get_user_agent`, body).then(res => {
            state.formData.base.userAgent.user_agent = res.data.user_agent
        })
    }

    const changeInherit = () => {
        if (state.formData.base.userAgent.inherit.includes('all') && state.formData.base.userAgent.inherit.length > 1) {
            state.formData.base.userAgent.inherit = state.formData.base.userAgent.inherit.filter(item => item !== 'all');
        }
        getUserAgent()
    }

    const createEnvironment = () => {
        console.log(state.formData);
        let body = JSON.parse(JSON.stringify(state.formData))
        let plantUser = []
        body.user.plantUser.forEach(item => {
            if (item.bc_type_id != '') {
                plantUser.push(item)
            }
        });
        body.user.plantUser = plantUser

        if (state.routeData.id == '') {
            http.post('/environment/creat_environment', body).then((res) => {
                ElMessage({
                    message: '创建成功',
                    type: 'success',
                })
                clickReturn()
            })
        } else {
            body.id = state.updateFormData.id
            body.number = state.updateFormData.number
            body.remark = state.updateFormData.remark ? state.updateFormData.remark : ''
            http.put('/environment/update_environment', body).then((res) => {
                ElMessage({
                    message: '修改成功',
                    type: 'success',
                })
                clickReturn()
            })
        }
    }


    onMounted(() => {
        state.map = initiaStores.initiaData.map
        
        
        state.formData_copy = initiaStores.initiaData.formData_copy
        state.routeData = route.query
        state.loading = true
        if (state.routeData.id == '') {
            state.title = "新建浏览器环境"
            state.menuList = [
                {
                    value: 'base',
                    label: '基础设置',
                    active: true,
                    scrollHeight: 0,
                    offsetTop: 0,
                    ref: null

                }, {
                    value: 'proxy',
                    label: '代理信息',
                    active: false,
                    scrollHeight: 0,
                    offsetTop: 0,
                    ref: null
                }, {
                    value: 'user',
                    label: '账号信息',
                    active: false,
                    scrollHeight: 0,
                    offsetTop: 0,
                    ref: null
                }, {
                    value: 'hign',
                    label: '高级设置',
                    active: false,
                    scrollHeight: 0,
                    offsetTop: 0,
                    ref: null
                },
            ]
            state.activeCollapse = ['base', 'proxy']
            http.get('/environment/get_environment_model').then((res) => {
                console.log(res);
                state.loading = false
                state.formData = res.data
                initData()
            }).catch(() => {
                state.loading = false
            })
        } else {
            state.title = "编辑浏览器环境"
            state.menuList = [
                {
                    value: 'base',
                    label: '基础设置',
                    active: true,
                    scrollHeight: 0,
                    offsetTop: 0,
                    ref: null

                }, {
                    value: 'user',
                    label: '账号信息',
                    active: false,
                    scrollHeight: 0,
                    offsetTop: 0,
                    ref: null
                }, {
                    value: 'hign',
                    label: '高级设置',
                    active: false,
                    scrollHeight: 0,
                    offsetTop: 0,
                    ref: null
                },
            ]
            state.activeCollapse = ['base']
            let params = {
                page: 1,
                page_size: 20,
                id: state.routeData.id
            }
            http.get('/environment/get_environments', { params }).then((res) => {
                state.loading = false
                if (res.data.list.length > 0) {
                    state.updateFormData = JSON.parse(JSON.stringify(res.data.list[0]))
                    state.formData = JSON.parse(JSON.stringify(res.data.list[0].environment_data))
                }

            })

        }

    })

    const initData = () => {
        getLanguages()
        getFonts()
        getTimeZones()
        getCountries()
        getPlatforms()
        getUaVersion()

        getUserAgent()
        getGroupList()
    }

    onUnmounted(() => {

    })

    return {
        state,

        clickReturn,
        clickmenu,
        clickcheckIP,
        clickcancelCheckip,
        changeProxyMode,
        getPhone,
        changeInherit,
        getUserAgent,
        createEnvironment,
        getPlatforms

    }
}
